# coding=utf-8
import httplib
import logging
import socket
import traceback
import urllib

import re
import requests
from pexpect import run

from config import BeetleConfig

log = logging.getLogger(__name__)

temp = run(
    '/bin/bash -c "/sbin/ifconfig -a eth0|grep inet|grep '
    '-v 127.0.0.1|'
    'grep -v inet6|awk \'{print $2}\'|tr -d \'addr:\'|head -1"')

temp_ip = re.sub(r"(.*)(\r\n)", r"\g<1>", temp)

ip = temp_ip


def is_open(port):
    s = socket.socket()
    try:
        s.settimeout(0.5)
        # s.connect_ex return 0 means port is open
        _is_open = s.connect_ex(('127.0.0.1', int(port))) == 0
    finally:
        s.close()

    return _is_open


def is_exists(path='/usr/local/app/none'):
    _p = run(
        '/bin/bash -c "ps -ef|grep %s |grep -v grep|awk \'NR==1{print $2}\'"' % path)

    return re.sub(r"(.*)(\r\n)", r"\g<1>", _p) != ''


def kill_progress_by_port(port):
    # 千万小心,这个方法可以kill掉自身, 一不小心把agent自己给kill了就玩笑开大了.

    print "杀掉占用端口的进程:%s" % str(port)

    cmd = '/bin/bash -c "lsof -i:%s|grep TCP|awk \'{print $2}\'|xargs kill -9;"' % str(
        port)

    return run(command=cmd, timeout=10, withexitstatus=True)


def get_ip():
    return run(
        '/bin/bash -c "/sbin/ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6|awk \'{print $2}\'|tr -d \'addr:\'|head -1"')


def call_agent_api(uri='', params=None, timeout=3, method='GET'):
    try:
        if params is not None:
            _params = urllib.urlencode(params)
        else:
            _params = None

        # httplib对post和get的参数传递方法略有不同, 一个放在uri里, 另一个要放到body里,不过格式是一样的,都是&和=隔开的字符串
        if method == 'GET':
            _uri = "%s%s?%s" % (
            BeetleConfig.UCLOUD_AGENT_API_CONTEXT, uri, _params)
            _body = None
        if method == 'POST':
            _uri = "%s%s" % (BeetleConfig.UCLOUD_AGENT_API_CONTEXT, uri)
            _body = _params

        httpClient = httplib.HTTPConnection(
            host=BeetleConfig.UCLOUD_AGENT_HOST,
            port=BeetleConfig.UCLOUD_AGENT_PORT,
            timeout=timeout)
        httpClient.request(method=method, url=_uri, body=_body)
        response = httpClient.getresponse().read()
        return response
    except:
        log.error("尝试调用API失败:url=%s , param:%s" % (str(_uri), params))
        log.error(traceback.format_exc())
        traceback.print_exc()
